const mysql = require('mysql')
const config = require('./default')

// 创建线程池
let pool = mysql.createPool({
    host:config.dataBase.HOST,
    user:config.dataBase.USERNAME,
    password:config.dataBase.PASSWORD,
    database:config.dataBase.DATABASE,
    port:config.dataBase.PORT
})

// 连接线程池，做sql查找
let allServices = {
    query: function(sql, values) {
        return new Promise((resolve, reject) => {
            pool.getConnection(function(err, connection) {
                if(err) {
                    reject(err)
                } else { // 连接成功
                    connection.query(sql, values, (err, rows) => {
                        if(err) {
                            reject(err)
                        } else {
                            resolve(rows)
                        }
                        connection.release() // 释放连接
                    })
                }
            }) 
        })
    }
}


// 用户登录
let userLogin = function(username, userpwd) {
    let _sql = `select * from users where username="${username}" and userpwd="${userpwd}";`
    return allServices.query(_sql)
}

// 查找用户
// 查找账号是否存在
let findUser = function(username){
    let _sql = `select * from users where username="${username}";`
    return allServices.query(_sql)
}

// 用户注册
let insertUser = function(value){
    let _sql = `insert into users set username=?,userpwd=?,nickname=?;`
    return allServices.query(_sql, value)    // value 一定要为数组
}

// 查找数据库是否有这个数据,并获取这个数据
// 根据类型查找文章列表
let catchData = function(nottype) {
    let _sql = `select * from note where note_type="${nottype}"`
    return allServices.query(_sql)
}

// 根据id查找获取详情
let find = function(id) {
    let _sql = `select * from note where id="${id}"`
    return allServices.query(_sql)
}

// 发布笔记
let Publish = function(value) {
    let _sql = `insert into note set note_content=?,title=?,head_img=?,note_type=?,useId=?,nickname=?,m_time=?,c_time=?;`
    return allServices.query(_sql, value)
}
module.exports = {
    userLogin,
    findUser,
    insertUser,
    catchData,
    find,
    Publish
}